import { dateFormat } from "@pkg";
import {
	CascaderType,
	DatePickerConf,
	FilterFormItemOptions,
	PySelectType,
	PySwitchType,
} from "./components";
import { FormItemOptions } from "./type";

const formatTime = (time: number) => {
	return dateFormat.formatTime(time);
};
const isFunction = (val: unknown): val is Function => {
	return val instanceof Function;
};
const isArray = (val: unknown): val is Array<any> => {
	return Array.isArray(val);
};

/** 解析日期 */
const parserDatePicker = (
	item: FormItemOptions<any> & {
		component: "DatePicker";
		conf?: FilterFormItemOptions<DatePickerConf>;
	}
) => {
	if (!item.conf || item.conf.type === "date") {
		const opt = item.value;
		const val = opt instanceof Array ? opt[0] : opt;
		return formatTime(val);
	} else {
		if (!isArray(item.value)) return "-- : --";
		const [first, last] = item.value;
		return formatTime(first) + " 至 " + formatTime(last);
	}
};

/** 解析选择器 */
const parserSelect = (
	item: FormItemOptions<any> & {
		component: "Select";
		conf?: FilterFormItemOptions<PySelectType>;
	}
) => {
	if (!item.conf) return item.value;
	const option = item.conf.options;
	if (isFunction(option)) {
		return option().then((opt: any) => {
			return opt.find((o: { value: any }) => o.value === item.value)?.label || "--";
		});
	} else {
		return option.find(o => o.value === item.value)?.label || "--";
	}
};

/** 解析 switch */
const parserSwitch = (
	item: FormItemOptions<any> & {
		component: "Switch";
		conf?: FilterFormItemOptions<PySwitchType>;
	}
) => {
	const targetVal = item.value;
	if (!item.conf) return targetVal;
	const s = item.conf.active.value === targetVal ? item.conf.active.label : "";
	const s1 = item.conf.inactive.value === targetVal ? item.conf.inactive.label : "";
	return s || s1;
};

/** 解析级联选择器 */
const parserCascader = async (
	item: FormItemOptions<any> & {
		component: "Cascader";
		conf?: FilterFormItemOptions<CascaderType>;
	}
) => {
	const { value, conf } = item;
	if (!item.conf) return value;
	const lazy = conf?.lazy;
	if (lazy) {
		// const load = await lazy.lazyLoad()
	}
};

export { parserDatePicker, parserSelect, parserSwitch, parserCascader };
